FusionDictionary.java revision 51a0ef8c59ea590b6e5e80a82fc75bf244084270
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.latin.makedict;
18
19import com.android.inputmethod.latin.Constants;
20
21import java.util.ArrayList;
22import java.util.Arrays;
23import java.util.Collections;
24import java.util.Date;
25import java.util.HashMap;
26import java.util.Iterator;
27import java.util.LinkedList;
28
29/**
30 * A dictionary that can fusion heads and tails of words for more compression.
31 */
32public final class FusionDictionary implements Iterable<Word> {
33    private static final boolean DBG = MakedictLog.DBG;
34
35    /**
36     * A node of the dictionary, containing several CharGroups.
37     *
38     * A node is but an ordered array of CharGroups, which essentially contain all the
39     * real information.
40     * This class also contains fields to cache size and address, to help with binary
41     * generation.
42     */
43    public static final class Node {
44        ArrayList<CharGroup> mData;
45        // To help with binary generation
46        int mCachedSize = Integer.MIN_VALUE;
47        int mCachedAddress = Integer.MIN_VALUE;
48        int mCachedParentAddress = 0;
49
50        public Node() {
51            mData = new ArrayList<CharGroup>();
52        }
53        public Node(ArrayList<CharGroup> data) {
54            mData = data;
55        }
56    }
57
58    /**
59     * A string with a frequency.
60     *
61     * This represents an "attribute", that is either a bigram or a shortcut.
62     */
63    public static final class WeightedString {
64        public final String mWord;
65        public int mFrequency;
66        public WeightedString(String word, int frequency) {
67            mWord = word;
68            mFrequency = frequency;
69        }
70
71        @Override
72        public int hashCode() {
73            return Arrays.hashCode(new Object[] { mWord, mFrequency });
74        }
75
76        @Override
77        public boolean equals(Object o) {
78            if (o == this) return true;
79            if (!(o instanceof WeightedString)) return false;
80            WeightedString w = (WeightedString)o;
81            return mWord.equals(w.mWord) && mFrequency == w.mFrequency;
82        }
83    }
84
85    /**
86     * A group of characters, with a frequency, shortcut targets, bigrams, and children.
87     *
88     * This is the central class of the in-memory representation. A CharGroup is what can
89     * be seen as a traditional "trie node", except it can hold several characters at the
90     * same time. A CharGroup essentially represents one or several characters in the middle
91     * of the trie trie; as such, it can be a terminal, and it can have children.
92     * In this in-memory representation, whether the CharGroup is a terminal or not is represented
93     * in the frequency, where NOT_A_TERMINAL (= -1) means this is not a terminal and any other
94     * value is the frequency of this terminal. A terminal may have non-null shortcuts and/or
95     * bigrams, but a non-terminal may not. Moreover, children, if present, are null.
96     */
97    public static final class CharGroup {
98        public static final int NOT_A_TERMINAL = -1;
99        final int mChars[];
100        ArrayList<WeightedString> mShortcutTargets;
101        ArrayList<WeightedString> mBigrams;
102        int mFrequency; // NOT_A_TERMINAL == mFrequency indicates this is not a terminal.
103        Node mChildren;
104        boolean mIsNotAWord; // Only a shortcut
105        boolean mIsBlacklistEntry;
106        // The two following members to help with binary generation
107        int mCachedSize;
108        int mCachedAddress;
109
110        public CharGroup(final int[] chars, final ArrayList<WeightedString> shortcutTargets,
111                final ArrayList<WeightedString> bigrams, final int frequency,
112                final boolean isNotAWord, final boolean isBlacklistEntry) {
113            mChars = chars;
114            mFrequency = frequency;
115            mShortcutTargets = shortcutTargets;
116            mBigrams = bigrams;
117            mChildren = null;
118            mIsNotAWord = isNotAWord;
119            mIsBlacklistEntry = isBlacklistEntry;
120        }
121
122        public CharGroup(final int[] chars, final ArrayList<WeightedString> shortcutTargets,
123                final ArrayList<WeightedString> bigrams, final int frequency,
124                final boolean isNotAWord, final boolean isBlacklistEntry, final Node children) {
125            mChars = chars;
126            mFrequency = frequency;
127            mShortcutTargets = shortcutTargets;
128            mBigrams = bigrams;
129            mChildren = children;
130            mIsNotAWord = isNotAWord;
131            mIsBlacklistEntry = isBlacklistEntry;
132        }
133
134        public void addChild(CharGroup n) {
135            if (null == mChildren) {
136                mChildren = new Node();
137            }
138            mChildren.mData.add(n);
139        }
140
141        public boolean isTerminal() {
142            return NOT_A_TERMINAL != mFrequency;
143        }
144
145        public int getFrequency() {
146            return mFrequency;
147        }
148
149        public boolean getIsNotAWord() {
150            return mIsNotAWord;
151        }
152
153        public boolean getIsBlacklistEntry() {
154            return mIsBlacklistEntry;
155        }
156
157        public ArrayList<WeightedString> getShortcutTargets() {
158            // We don't want write permission to escape outside the package, so we return a copy
159            if (null == mShortcutTargets) return null;
160            final ArrayList<WeightedString> copyOfShortcutTargets =
161                    new ArrayList<WeightedString>(mShortcutTargets);
162            return copyOfShortcutTargets;
163        }
164
165        public ArrayList<WeightedString> getBigrams() {
166            // We don't want write permission to escape outside the package, so we return a copy
167            if (null == mBigrams) return null;
168            final ArrayList<WeightedString> copyOfBigrams = new ArrayList<WeightedString>(mBigrams);
169            return copyOfBigrams;
170        }
171
172        public boolean hasSeveralChars() {
173            assert(mChars.length > 0);
174            return 1 < mChars.length;
175        }
176
177        /**
178         * Adds a word to the bigram list. Updates the frequency if the word already
179         * exists.
180         */
181        public void addBigram(final String word, final int frequency) {
182            if (mBigrams == null) {
183                mBigrams = new ArrayList<WeightedString>();
184            }
185            WeightedString bigram = getBigram(word);
186            if (bigram != null) {
187                bigram.mFrequency = frequency;
188            } else {
189                bigram = new WeightedString(word, frequency);
190                mBigrams.add(bigram);
191            }
192        }
193
194        /**
195         * Gets the shortcut target for the given word. Returns null if the word is not in the
196         * shortcut list.
197         */
198        public WeightedString getShortcut(final String word) {
199            // TODO: Don't do a linear search
200            if (mShortcutTargets != null) {
201                final int size = mShortcutTargets.size();
202                for (int i = 0; i < size; ++i) {
203                    WeightedString shortcut = mShortcutTargets.get(i);
204                    if (shortcut.mWord.equals(word)) {
205                        return shortcut;
206                    }
207                }
208            }
209            return null;
210        }
211
212        /**
213         * Gets the bigram for the given word.
214         * Returns null if the word is not in the bigrams list.
215         */
216        public WeightedString getBigram(final String word) {
217            // TODO: Don't do a linear search
218            if (mBigrams != null) {
219                final int size = mBigrams.size();
220                for (int i = 0; i < size; ++i) {
221                    WeightedString bigram = mBigrams.get(i);
222                    if (bigram.mWord.equals(word)) {
223                        return bigram;
224                    }
225                }
226            }
227            return null;
228        }
229
230        /**
231         * Updates the CharGroup with the given properties. Adds the shortcut and bigram lists to
232         * the existing ones if any. Note: unigram, bigram, and shortcut frequencies are only
233         * updated if they are higher than the existing ones.
234         */
235        public void update(final int frequency, final ArrayList<WeightedString> shortcutTargets,
236                final ArrayList<WeightedString> bigrams,
237                final boolean isNotAWord, final boolean isBlacklistEntry) {
238            if (frequency > mFrequency) {
239                mFrequency = frequency;
240            }
241            if (shortcutTargets != null) {
242                if (mShortcutTargets == null) {
243                    mShortcutTargets = shortcutTargets;
244                } else {
245                    final int size = shortcutTargets.size();
246                    for (int i = 0; i < size; ++i) {
247                        final WeightedString shortcut = shortcutTargets.get(i);
248                        final WeightedString existingShortcut = getShortcut(shortcut.mWord);
249                        if (existingShortcut == null) {
250                            mShortcutTargets.add(shortcut);
251                        } else if (existingShortcut.mFrequency < shortcut.mFrequency) {
252                            existingShortcut.mFrequency = shortcut.mFrequency;
253                        }
254                    }
255                }
256            }
257            if (bigrams != null) {
258                if (mBigrams == null) {
259                    mBigrams = bigrams;
260                } else {
261                    final int size = bigrams.size();
262                    for (int i = 0; i < size; ++i) {
263                        final WeightedString bigram = bigrams.get(i);
264                        final WeightedString existingBigram = getBigram(bigram.mWord);
265                        if (existingBigram == null) {
266                            mBigrams.add(bigram);
267                        } else if (existingBigram.mFrequency < bigram.mFrequency) {
268                            existingBigram.mFrequency = bigram.mFrequency;
269                        }
270                    }
271                }
272            }
273            mIsNotAWord = isNotAWord;
274            mIsBlacklistEntry = isBlacklistEntry;
275        }
276    }
277
278    /**
279     * Options global to the dictionary.
280     */
281    public static final class DictionaryOptions {
282        public final boolean mGermanUmlautProcessing;
283        public final boolean mFrenchLigatureProcessing;
284        public final HashMap<String, String> mAttributes;
285        public DictionaryOptions(final HashMap<String, String> attributes,
286                final boolean germanUmlautProcessing, final boolean frenchLigatureProcessing) {
287            mAttributes = attributes;
288            mGermanUmlautProcessing = germanUmlautProcessing;
289            mFrenchLigatureProcessing = frenchLigatureProcessing;
290        }
291        @Override
292        public String toString() { // Convenience method
293            return toString(0, false);
294        }
295        public String toString(final int indentCount, final boolean plumbing) {
296            final StringBuilder indent = new StringBuilder();
297            if (plumbing) {
298                indent.append("H:");
299            } else {
300                for (int i = 0; i < indentCount; ++i) {
301                    indent.append(" ");
302                }
303            }
304            final StringBuilder s = new StringBuilder();
305            for (final String optionKey : mAttributes.keySet()) {
306                s.append(indent);
307                s.append(optionKey);
308                s.append(" = ");
309                if ("date".equals(optionKey) && !plumbing) {
310                    // Date needs a number of milliseconds, but the dictionary contains seconds
311                    s.append(new Date(
312                            1000 * Long.parseLong(mAttributes.get(optionKey))).toString());
313                } else {
314                    s.append(mAttributes.get(optionKey));
315                }
316                s.append("\n");
317            }
318            if (mGermanUmlautProcessing) {
319                s.append(indent);
320                s.append("Needs German umlaut processing\n");
321            }
322            if (mFrenchLigatureProcessing) {
323                s.append(indent);
324                s.append("Needs French ligature processing\n");
325            }
326            return s.toString();
327        }
328    }
329
330    public final DictionaryOptions mOptions;
331    public final Node mRoot;
332
333    public FusionDictionary(final Node root, final DictionaryOptions options) {
334        mRoot = root;
335        mOptions = options;
336    }
337
338    public void addOptionAttribute(final String key, final String value) {
339        mOptions.mAttributes.put(key, value);
340    }
341
342    /**
343     * Helper method to convert a String to an int array.
344     */
345    static int[] getCodePoints(final String word) {
346        // TODO: this is a copy-paste of the contents of StringUtils.toCodePointArray,
347        // which is not visible from the makedict package. Factor this code.
348        final char[] characters = word.toCharArray();
349        final int length = characters.length;
350        final int[] codePoints = new int[Character.codePointCount(characters, 0, length)];
351        int codePoint = Character.codePointAt(characters, 0);
352        int dsti = 0;
353        for (int srci = Character.charCount(codePoint);
354                srci < length; srci += Character.charCount(codePoint), ++dsti) {
355            codePoints[dsti] = codePoint;
356            codePoint = Character.codePointAt(characters, srci);
357        }
358        codePoints[dsti] = codePoint;
359        return codePoints;
360    }
361
362    /**
363     * Helper method to add a word as a string.
364     *
365     * This method adds a word to the dictionary with the given frequency. Optional
366     * lists of bigrams and shortcuts can be passed here. For each word inside,
367     * they will be added to the dictionary as necessary.
368     *
369     * @param word the word to add.
370     * @param frequency the frequency of the word, in the range [0..255].
371     * @param shortcutTargets a list of shortcut targets for this word, or null.
372     * @param isNotAWord true if this should not be considered a word (e.g. shortcut only)
373     */
374    public void add(final String word, final int frequency,
375            final ArrayList<WeightedString> shortcutTargets, final boolean isNotAWord) {
376        add(getCodePoints(word), frequency, shortcutTargets, isNotAWord,
377                false /* isBlacklistEntry */);
378    }
379
380    /**
381     * Helper method to add a blacklist entry as a string.
382     *
383     * @param word the word to add as a blacklist entry.
384     * @param shortcutTargets a list of shortcut targets for this word, or null.
385     * @param isNotAWord true if this is not a word for spellcheking purposes (shortcut only or so)
386     */
387    public void addBlacklistEntry(final String word,
388            final ArrayList<WeightedString> shortcutTargets, final boolean isNotAWord) {
389        add(getCodePoints(word), 0, shortcutTargets, isNotAWord, true /* isBlacklistEntry */);
390    }
391
392    /**
393     * Sanity check for a node.
394     *
395     * This method checks that all CharGroups in a node are ordered as expected.
396     * If they are, nothing happens. If they aren't, an exception is thrown.
397     */
398    private void checkStack(Node node) {
399        ArrayList<CharGroup> stack = node.mData;
400        int lastValue = -1;
401        for (int i = 0; i < stack.size(); ++i) {
402            int currentValue = stack.get(i).mChars[0];
403            if (currentValue <= lastValue)
404                throw new RuntimeException("Invalid stack");
405            else
406                lastValue = currentValue;
407        }
408    }
409
410    /**
411     * Helper method to add a new bigram to the dictionary.
412     *
413     * @param word1 the previous word of the context
414     * @param word2 the next word of the context
415     * @param frequency the bigram frequency
416     */
417    public void setBigram(final String word1, final String word2, final int frequency) {
418        CharGroup charGroup = findWordInTree(mRoot, word1);
419        if (charGroup != null) {
420            final CharGroup charGroup2 = findWordInTree(mRoot, word2);
421            if (charGroup2 == null) {
422                add(getCodePoints(word2), 0, null, false /* isNotAWord */,
423                        false /* isBlacklistEntry */);
424                // The chargroup for the first word may have moved by the above insertion,
425                // if word1 and word2 share a common stem that happens not to have been
426                // a cutting point until now. In this case, we need to refresh charGroup.
427                charGroup = findWordInTree(mRoot, word1);
428            }
429            charGroup.addBigram(word2, frequency);
430        } else {
431            throw new RuntimeException("First word of bigram not found");
432        }
433    }
434
435    /**
436     * Add a word to this dictionary.
437     *
438     * The shortcuts, if any, have to be in the dictionary already. If they aren't,
439     * an exception is thrown.
440     *
441     * @param word the word, as an int array.
442     * @param frequency the frequency of the word, in the range [0..255].
443     * @param shortcutTargets an optional list of shortcut targets for this word (null if none).
444     * @param isNotAWord true if this is not a word for spellcheking purposes (shortcut only or so)
445     * @param isBlacklistEntry true if this is a blacklisted word, false otherwise
446     */
447    private void add(final int[] word, final int frequency,
448            final ArrayList<WeightedString> shortcutTargets,
449            final boolean isNotAWord, final boolean isBlacklistEntry) {
450        assert(frequency >= 0 && frequency <= 255);
451        if (word.length >= Constants.Dictionary.MAX_WORD_LENGTH) {
452            MakedictLog.w("Ignoring a word that is too long: word.length = " + word.length);
453            return;
454        }
455
456        Node currentNode = mRoot;
457        int charIndex = 0;
458
459        CharGroup currentGroup = null;
460        int differentCharIndex = 0; // Set by the loop to the index of the char that differs
461        int nodeIndex = findIndexOfChar(mRoot, word[charIndex]);
462        while (CHARACTER_NOT_FOUND != nodeIndex) {
463            currentGroup = currentNode.mData.get(nodeIndex);
464            differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex);
465            if (ARRAYS_ARE_EQUAL != differentCharIndex
466                    && differentCharIndex < currentGroup.mChars.length) break;
467            if (null == currentGroup.mChildren) break;
468            charIndex += currentGroup.mChars.length;
469            if (charIndex >= word.length) break;
470            currentNode = currentGroup.mChildren;
471            nodeIndex = findIndexOfChar(currentNode, word[charIndex]);
472        }
473
474        if (-1 == nodeIndex) {
475            // No node at this point to accept the word. Create one.
476            final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]);
477            final CharGroup newGroup = new CharGroup(
478                    Arrays.copyOfRange(word, charIndex, word.length),
479                    shortcutTargets, null /* bigrams */, frequency, isNotAWord, isBlacklistEntry);
480            currentNode.mData.add(insertionIndex, newGroup);
481            if (DBG) checkStack(currentNode);
482        } else {
483            // There is a word with a common prefix.
484            if (differentCharIndex == currentGroup.mChars.length) {
485                if (charIndex + differentCharIndex >= word.length) {
486                    // The new word is a prefix of an existing word, but the node on which it
487                    // should end already exists as is. Since the old CharNode was not a terminal,
488                    // make it one by filling in its frequency and other attributes
489                    currentGroup.update(frequency, shortcutTargets, null, isNotAWord,
490                            isBlacklistEntry);
491                } else {
492                    // The new word matches the full old word and extends past it.
493                    // We only have to create a new node and add it to the end of this.
494                    final CharGroup newNode = new CharGroup(
495                            Arrays.copyOfRange(word, charIndex + differentCharIndex, word.length),
496                                    shortcutTargets, null /* bigrams */, frequency, isNotAWord,
497                                    isBlacklistEntry);
498                    currentGroup.mChildren = new Node();
499                    currentGroup.mChildren.mData.add(newNode);
500                }
501            } else {
502                if (0 == differentCharIndex) {
503                    // Exact same word. Update the frequency if higher. This will also add the
504                    // new shortcuts to the existing shortcut list if it already exists.
505                    currentGroup.update(frequency, shortcutTargets, null,
506                            currentGroup.mIsNotAWord && isNotAWord,
507                            currentGroup.mIsBlacklistEntry || isBlacklistEntry);
508                } else {
509                    // Partial prefix match only. We have to replace the current node with a node
510                    // containing the current prefix and create two new ones for the tails.
511                    Node newChildren = new Node();
512                    final CharGroup newOldWord = new CharGroup(
513                            Arrays.copyOfRange(currentGroup.mChars, differentCharIndex,
514                                    currentGroup.mChars.length), currentGroup.mShortcutTargets,
515                            currentGroup.mBigrams, currentGroup.mFrequency,
516                            currentGroup.mIsNotAWord, currentGroup.mIsBlacklistEntry,
517                            currentGroup.mChildren);
518                    newChildren.mData.add(newOldWord);
519
520                    final CharGroup newParent;
521                    if (charIndex + differentCharIndex >= word.length) {
522                        newParent = new CharGroup(
523                                Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
524                                shortcutTargets, null /* bigrams */, frequency,
525                                isNotAWord, isBlacklistEntry, newChildren);
526                    } else {
527                        newParent = new CharGroup(
528                                Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
529                                null /* shortcutTargets */, null /* bigrams */, -1,
530                                false /* isNotAWord */, false /* isBlacklistEntry */, newChildren);
531                        final CharGroup newWord = new CharGroup(Arrays.copyOfRange(word,
532                                charIndex + differentCharIndex, word.length),
533                                shortcutTargets, null /* bigrams */, frequency,
534                                isNotAWord, isBlacklistEntry);
535                        final int addIndex = word[charIndex + differentCharIndex]
536                                > currentGroup.mChars[differentCharIndex] ? 1 : 0;
537                        newChildren.mData.add(addIndex, newWord);
538                    }
539                    currentNode.mData.set(nodeIndex, newParent);
540                }
541                if (DBG) checkStack(currentNode);
542            }
543        }
544    }
545
546    private static int ARRAYS_ARE_EQUAL = 0;
547
548    /**
549     * Custom comparison of two int arrays taken to contain character codes.
550     *
551     * This method compares the two arrays passed as an argument in a lexicographic way,
552     * with an offset in the dst string.
553     * This method does NOT test for the first character. It is taken to be equal.
554     * I repeat: this method starts the comparison at 1 <> dstOffset + 1.
555     * The index where the strings differ is returned. ARRAYS_ARE_EQUAL = 0 is returned if the
556     * strings are equal. This works BECAUSE we don't look at the first character.
557     *
558     * @param src the left-hand side string of the comparison.
559     * @param dst the right-hand side string of the comparison.
560     * @param dstOffset the offset in the right-hand side string.
561     * @return the index at which the strings differ, or ARRAYS_ARE_EQUAL = 0 if they don't.
562     */
563    private static int compareArrays(final int[] src, final int[] dst, int dstOffset) {
564        // We do NOT test the first char, because we come from a method that already
565        // tested it.
566        for (int i = 1; i < src.length; ++i) {
567            if (dstOffset + i >= dst.length) return i;
568            if (src[i] != dst[dstOffset + i]) return i;
569        }
570        if (dst.length > src.length) return src.length;
571        return ARRAYS_ARE_EQUAL;
572    }
573
574    /**
575     * Helper class that compares and sorts two chargroups according to their
576     * first element only. I repeat: ONLY the first element is considered, the rest
577     * is ignored.
578     * This comparator imposes orderings that are inconsistent with equals.
579     */
580    static private final class CharGroupComparator implements java.util.Comparator<CharGroup> {
581        @Override
582        public int compare(CharGroup c1, CharGroup c2) {
583            if (c1.mChars[0] == c2.mChars[0]) return 0;
584            return c1.mChars[0] < c2.mChars[0] ? -1 : 1;
585        }
586    }
587    final static private CharGroupComparator CHARGROUP_COMPARATOR = new CharGroupComparator();
588
589    /**
590     * Finds the insertion index of a character within a node.
591     */
592    private static int findInsertionIndex(final Node node, int character) {
593        final ArrayList<CharGroup> data = node.mData;
594        final CharGroup reference = new CharGroup(new int[] { character },
595                null /* shortcutTargets */, null /* bigrams */, 0, false /* isNotAWord */,
596                false /* isBlacklistEntry */);
597        int result = Collections.binarySearch(data, reference, CHARGROUP_COMPARATOR);
598        return result >= 0 ? result : -result - 1;
599    }
600
601    private static int CHARACTER_NOT_FOUND = -1;
602
603    /**
604     * Find the index of a char in a node, if it exists.
605     *
606     * @param node the node to search in.
607     * @param character the character to search for.
608     * @return the position of the character if it's there, or CHARACTER_NOT_FOUND = -1 else.
609     */
610    private static int findIndexOfChar(final Node node, int character) {
611        final int insertionIndex = findInsertionIndex(node, character);
612        if (node.mData.size() <= insertionIndex) return CHARACTER_NOT_FOUND;
613        return character == node.mData.get(insertionIndex).mChars[0] ? insertionIndex
614                : CHARACTER_NOT_FOUND;
615    }
616
617    /**
618     * Helper method to find a word in a given branch.
619     */
620    public static CharGroup findWordInTree(Node node, final String s) {
621        int index = 0;
622        final StringBuilder checker = DBG ? new StringBuilder() : null;
623
624        CharGroup currentGroup;
625        final int codePointCountInS = s.codePointCount(0, s.length());
626        do {
627            int indexOfGroup = findIndexOfChar(node, s.codePointAt(index));
628            if (CHARACTER_NOT_FOUND == indexOfGroup) return null;
629            currentGroup = node.mData.get(indexOfGroup);
630
631            if (s.length() - index < currentGroup.mChars.length) return null;
632            int newIndex = index;
633            while (newIndex < s.length() && newIndex - index < currentGroup.mChars.length) {
634                if (currentGroup.mChars[newIndex - index] != s.codePointAt(newIndex)) return null;
635                newIndex++;
636            }
637            index = newIndex;
638
639            if (DBG) checker.append(new String(currentGroup.mChars, 0, currentGroup.mChars.length));
640            if (index < codePointCountInS) {
641                node = currentGroup.mChildren;
642            }
643        } while (null != node && index < codePointCountInS);
644
645        if (index < codePointCountInS) return null;
646        if (!currentGroup.isTerminal()) return null;
647        if (DBG && !s.equals(checker.toString())) return null;
648        return currentGroup;
649    }
650
651    /**
652     * Helper method to find out whether a word is in the dict or not.
653     */
654    public boolean hasWord(final String s) {
655        if (null == s || "".equals(s)) {
656            throw new RuntimeException("Can't search for a null or empty string");
657        }
658        return null != findWordInTree(mRoot, s);
659    }
660
661    /**
662     * Recursively count the number of character groups in a given branch of the trie.
663     *
664     * @param node the parent node.
665     * @return the number of char groups in all the branch under this node.
666     */
667    public static int countCharGroups(final Node node) {
668        final int nodeSize = node.mData.size();
669        int size = nodeSize;
670        for (int i = nodeSize - 1; i >= 0; --i) {
671            CharGroup group = node.mData.get(i);
672            if (null != group.mChildren)
673                size += countCharGroups(group.mChildren);
674        }
675        return size;
676    }
677
678    /**
679     * Recursively count the number of nodes in a given branch of the trie.
680     *
681     * @param node the node to count.
682     * @return the number of nodes in this branch.
683     */
684    public static int countNodes(final Node node) {
685        int size = 1;
686        for (int i = node.mData.size() - 1; i >= 0; --i) {
687            CharGroup group = node.mData.get(i);
688            if (null != group.mChildren)
689                size += countNodes(group.mChildren);
690        }
691        return size;
692    }
693
694    // Recursively find out whether there are any bigrams.
695    // This can be pretty expensive especially if there aren't any (we return as soon
696    // as we find one, so it's much cheaper if there are bigrams)
697    private static boolean hasBigramsInternal(final Node node) {
698        if (null == node) return false;
699        for (int i = node.mData.size() - 1; i >= 0; --i) {
700            CharGroup group = node.mData.get(i);
701            if (null != group.mBigrams) return true;
702            if (hasBigramsInternal(group.mChildren)) return true;
703        }
704        return false;
705    }
706
707    /**
708     * Finds out whether there are any bigrams in this dictionary.
709     *
710     * @return true if there is any bigram, false otherwise.
711     */
712    // TODO: this is expensive especially for large dictionaries without any bigram.
713    // The up side is, this is always accurate and correct and uses no memory. We should
714    // find a more efficient way of doing this, without compromising too much on memory
715    // and ease of use.
716    public boolean hasBigrams() {
717        return hasBigramsInternal(mRoot);
718    }
719
720    // Historically, the tails of the words were going to be merged to save space.
721    // However, that would prevent the code to search for a specific address in log(n)
722    // time so this was abandoned.
723    // The code is still of interest as it does add some compression to any dictionary
724    // that has no need for attributes. Implementations that does not read attributes should be
725    // able to read a dictionary with merged tails.
726    // Also, the following code does support frequencies, as in, it will only merges
727    // tails that share the same frequency. Though it would result in the above loss of
728    // performance while searching by address, it is still technically possible to merge
729    // tails that contain attributes, but this code does not take that into account - it does
730    // not compare attributes and will merge terminals with different attributes regardless.
731    public void mergeTails() {
732        MakedictLog.i("Do not merge tails");
733        return;
734
735//        MakedictLog.i("Merging nodes. Number of nodes : " + countNodes(root));
736//        MakedictLog.i("Number of groups : " + countCharGroups(root));
737//
738//        final HashMap<String, ArrayList<Node>> repository =
739//                  new HashMap<String, ArrayList<Node>>();
740//        mergeTailsInner(repository, root);
741//
742//        MakedictLog.i("Number of different pseudohashes : " + repository.size());
743//        int size = 0;
744//        for (ArrayList<Node> a : repository.values()) {
745//            size += a.size();
746//        }
747//        MakedictLog.i("Number of nodes after merge : " + (1 + size));
748//        MakedictLog.i("Recursively seen nodes : " + countNodes(root));
749    }
750
751    // The following methods are used by the deactivated mergeTails()
752//   private static boolean isEqual(Node a, Node b) {
753//       if (null == a && null == b) return true;
754//       if (null == a || null == b) return false;
755//       if (a.data.size() != b.data.size()) return false;
756//       final int size = a.data.size();
757//       for (int i = size - 1; i >= 0; --i) {
758//           CharGroup aGroup = a.data.get(i);
759//           CharGroup bGroup = b.data.get(i);
760//           if (aGroup.frequency != bGroup.frequency) return false;
761//           if (aGroup.alternates == null && bGroup.alternates != null) return false;
762//           if (aGroup.alternates != null && !aGroup.equals(bGroup.alternates)) return false;
763//           if (!Arrays.equals(aGroup.chars, bGroup.chars)) return false;
764//           if (!isEqual(aGroup.children, bGroup.children)) return false;
765//       }
766//       return true;
767//   }
768
769//   static private HashMap<String, ArrayList<Node>> mergeTailsInner(
770//           final HashMap<String, ArrayList<Node>> map, final Node node) {
771//       final ArrayList<CharGroup> branches = node.data;
772//       final int nodeSize = branches.size();
773//       for (int i = 0; i < nodeSize; ++i) {
774//           CharGroup group = branches.get(i);
775//           if (null != group.children) {
776//               String pseudoHash = getPseudoHash(group.children);
777//               ArrayList<Node> similarList = map.get(pseudoHash);
778//               if (null == similarList) {
779//                   similarList = new ArrayList<Node>();
780//                   map.put(pseudoHash, similarList);
781//               }
782//               boolean merged = false;
783//               for (Node similar : similarList) {
784//                   if (isEqual(group.children, similar)) {
785//                       group.children = similar;
786//                       merged = true;
787//                       break;
788//                   }
789//               }
790//               if (!merged) {
791//                   similarList.add(group.children);
792//               }
793//               mergeTailsInner(map, group.children);
794//           }
795//       }
796//       return map;
797//   }
798
799//  private static String getPseudoHash(final Node node) {
800//      StringBuilder s = new StringBuilder();
801//      for (CharGroup g : node.data) {
802//          s.append(g.frequency);
803//          for (int ch : g.chars) {
804//              s.append(Character.toChars(ch));
805//          }
806//      }
807//      return s.toString();
808//  }
809
810    /**
811     * Iterator to walk through a dictionary.
812     *
813     * This is purely for convenience.
814     */
815    public static final class DictionaryIterator implements Iterator<Word> {
816        private static final class Position {
817            public Iterator<CharGroup> pos;
818            public int length;
819            public Position(ArrayList<CharGroup> groups) {
820                pos = groups.iterator();
821                length = 0;
822            }
823        }
824        final StringBuilder mCurrentString;
825        final LinkedList<Position> mPositions;
826
827        public DictionaryIterator(ArrayList<CharGroup> root) {
828            mCurrentString = new StringBuilder();
829            mPositions = new LinkedList<Position>();
830            final Position rootPos = new Position(root);
831            mPositions.add(rootPos);
832        }
833
834        @Override
835        public boolean hasNext() {
836            for (Position p : mPositions) {
837                if (p.pos.hasNext()) {
838                    return true;
839                }
840            }
841            return false;
842        }
843
844        @Override
845        public Word next() {
846            Position currentPos = mPositions.getLast();
847            mCurrentString.setLength(mCurrentString.length() - currentPos.length);
848
849            do {
850                if (currentPos.pos.hasNext()) {
851                    final CharGroup currentGroup = currentPos.pos.next();
852                    currentPos.length = currentGroup.mChars.length;
853                    for (int i : currentGroup.mChars)
854                        mCurrentString.append(Character.toChars(i));
855                    if (null != currentGroup.mChildren) {
856                        currentPos = new Position(currentGroup.mChildren.mData);
857                        mPositions.addLast(currentPos);
858                    }
859                    if (currentGroup.mFrequency >= 0)
860                        return new Word(mCurrentString.toString(), currentGroup.mFrequency,
861                                currentGroup.mShortcutTargets, currentGroup.mBigrams,
862                                currentGroup.mIsNotAWord, currentGroup.mIsBlacklistEntry);
863                } else {
864                    mPositions.removeLast();
865                    currentPos = mPositions.getLast();
866                    mCurrentString.setLength(mCurrentString.length() - mPositions.getLast().length);
867                }
868            } while (true);
869        }
870
871        @Override
872        public void remove() {
873            throw new UnsupportedOperationException("Unsupported yet");
874        }
875
876    }
877
878    /**
879     * Method to return an iterator.
880     *
881     * This method enables Java's enhanced for loop. With this you can have a FusionDictionary x
882     * and say : for (Word w : x) {}
883     */
884    @Override
885    public Iterator<Word> iterator() {
886        return new DictionaryIterator(mRoot.mData);
887    }
888}
889